// server/api/file/download.ts
import { defineEventHandler, getQuery } from 'h3'

export default defineEventHandler(async (event) => {
  const { url } = getQuery(event)
  if (!url || typeof url !== 'string') {
    event.res.statusCode = 400
    return { error: '缺少 url 参数' }
  }

  const upstream = await fetch(url)
  if (!upstream.ok) {
    event.res.statusCode = upstream.status
    return { error: `上游请求失败：${upstream.status}` }
  }

  // 透传 Content-Type
  const contentType = upstream.headers.get('content-type') || 'application/octet-stream'
  event.res.setHeader('Content-Type', contentType)

  // 透传 Content-Disposition（中文文件名支持）
  const rawName = new URL(url).pathname.split('/').pop() || 'file.bin'
  const filename = decodeURIComponent(rawName)
  event.res.setHeader(
    'Content-Disposition',
    `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`
  )

  // ★ 透传 Content-Length，关键一步！
  const length = upstream.headers.get('content-length')
  if (length) {
    event.res.setHeader('Content-Length', length)
  }

  // 开始流式写入
  const reader  = upstream.body!.getReader()
  const nodeRes = event.node.res

  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    nodeRes.write(Buffer.from(value!))
  }
  nodeRes.end()
})
